package nl.ajonker.railroad.dl;

import nl.ajonker.railroad.bl.NetworkSwitchAddress;
import nl.ajonker.railroad.sl.SwitchListener;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;

public class Track {
    private final LinkedHashMap<String, SwitchRail> rails = new LinkedHashMap<String, SwitchRail>();
    private final LinkedList<SwitchListener> listeners = new LinkedList<SwitchListener>();

    public Track() {
        addRail(new SwitchRail("1", new NetworkSwitchAddress(0, 0)));
        addRail(new SwitchRail("2", new NetworkSwitchAddress(0, 1)));
        addRail(new SwitchRail("3", new NetworkSwitchAddress(0, 2)));
        addRail(new SwitchRail("4", new NetworkSwitchAddress(1, 0)));
        addRail(new SwitchRail("5", new NetworkSwitchAddress(1, 1)));
        addRail(new SwitchRail("6", new NetworkSwitchAddress(1, 2)));
        addRail(new SwitchRail("7", new NetworkSwitchAddress(0, 3)));
        addRail(new SwitchRail("8", new NetworkSwitchAddress(0, 4)));
        addRail(new SwitchRail("9", new NetworkSwitchAddress(0, 5)));
        addRail(new SwitchRail("10", new NetworkSwitchAddress(1, 5)));
        addRail(new SwitchRail("11", new NetworkSwitchAddress(1, 4)));
        addRail(new SwitchRail("12", new NetworkSwitchAddress(1, 3)));
        addRail(new SwitchRail("13", new NetworkSwitchAddress(0, 6)));
        addRail(new SwitchRail("14", new NetworkSwitchAddress(1, 6)));
    }

    private void addRail(SwitchRail rail) {
        rails.put(rail.getName(), rail);
    }

    public void addListener(SwitchListener listener) {
        listeners.add(listener);
    }

    public void switchRailPosition(String name) {
        SwitchRail rail = rails.get(name);
        boolean success = true;
        for (SwitchListener listener : listeners) {
            if (!listener.onSwitch(rail))
                success = false;
        }
        if (success)
            rail.switchPosition();
    }

    public SwitchRail getRail(String name) {
        return rails.get(name);
    }

    public List<SwitchRail> getRails() {
        return new ArrayList<SwitchRail>(rails.values());
    }
}
